package com.xxxy.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.xxxy.model.AdministrativeClass;
import com.xxxy.model.Faculty;
import com.xxxy.service.AdministrativeClassService;
import com.xxxy.util.SpringApplicationUtils;
import org.apache.shiro.util.CollectionUtils;

import java.util.Map;

/**
 * @author sjh
 * @date 2022/2/1 16:13
 */
public class AdministrativeClassConverter implements Converter<Integer> {

    private static Map<Integer,String> statusMap = null;

    AdministrativeClassService administrativeClassService= SpringApplicationUtils.getBean(AdministrativeClassService.class);

    //懒汉模式构造器，将状态码映射关系注入进map中，不必每次都连接数据库进行查询
    public AdministrativeClassConverter(){
        if(CollectionUtils.isEmpty(statusMap)){
            statusMap = administrativeClassService.getItemMap();
        }
    }

    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String stringValue = cellData.getStringValue();
        for(Integer integer: statusMap.keySet()){
            if(stringValue.equals(statusMap.get(integer))){
                return integer;
            }
        }
        AdministrativeClass administrativeClass = administrativeClassService.getByName(stringValue);
        if(administrativeClass != null){
            statusMap.put(administrativeClass.getId(), administrativeClass.getClassName());
            return administrativeClass.getId();
        }
        //没有该行政班级
        return 0;
    }

    @Override
    public CellData convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String administrativeName = statusMap.get(integer);
        if(administrativeName == null){
            AdministrativeClass administrativeClass = administrativeClassService.getById(integer);
            if(administrativeClass != null){
                statusMap.put(administrativeClass.getId(), administrativeClass.getClassName());
                return new CellData(administrativeClass.getClassName());
            }
            return new CellData("");
        }
        return new CellData(administrativeName);
    }
}
